// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace SnapObjects.Data.AspNetCore
{
    internal class ModelBinderProvider : IModelBinderProvider
    {
        private readonly IList<IDataFormater> _formaters;

        public ModelBinderProvider()
        {
            _formaters = new List<IDataFormater>()
            {
                new DataPackerFormater(),
                new DataUnpackerFormater()
            };
        }

        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            var dataType = context.Metadata.ModelType;

            var formater = this.GetDataFormater(dataType);

            if (formater != null)
            {
                return new ModelBinder(formater);
            }

            return null;
        }

        private IDataFormater GetDataFormater(Type dataType)
        {
            foreach (var formater in _formaters)
            {
                if (formater.CanFormat(dataType))
                {
                    return formater;
                }
            }

            return null;
        }
    }
}
